package com.yswee.framework.utils;

import java.net.URISyntaxException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.yswee.framework.Application;
import com.yswee.framework.R;
import com.yswee.framework.manager.ActivityManager;
import com.yswee.framework.widget.MToast;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.util.Log;

public class LocationUtils {
	
	public static final String PACKAGENAME_BAIDUMAP = "com.baidu.BaiduMap";
	public static final String PACKAGENAME_AMAP = "com.autonavi.minimap";
	
	private static double EARTH_RADIUS = 6378.137; 
	   
	private static double getRadian(double degree) {  
        return degree * Math.PI / 180.0;  
    }
    
	public static boolean isValid(Location location) {
		if (location == null) {
			return false;
		}
		double lat = location.getLatitude();
		double lon = location.getLongitude();
		return isValid(lat, lon);
	}
    
	public static boolean isValid(double lat, double lon) {
		if (lon < 73.4d || lon > 135.2d) {
			return false;
		}
		if (lat < 3.5d || lat > 53.3d) {
			return false;
		}
		return true;
	}
	
	public static String getFormatDistance(double lat1, double lng1, double lat2, double lng2) {
		double radLat1 = getRadian(lat1);  
        double radLat2 = getRadian(lat2);  
        double a = radLat1 - radLat2;// 两点纬度差  
        double b = getRadian(lng1) - getRadian(lng2);// 两点的经度差  
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1)  
                * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));  
        s = s * EARTH_RADIUS;  
        double distance = s * 1000;  
        if (distance >= 1000) {
        	return new DecimalFormat("#.0km").format(distance * 1.0f / 1000);
        } else {
        	return new DecimalFormat("0m").format(distance);
        }
	}
	
	public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
		double radLat1 = getRadian(lat1);  
        double radLat2 = getRadian(lat2);  
        double a = radLat1 - radLat2;// 两点纬度差  
        double b = getRadian(lng1) - getRadian(lng2);// 两点的经度差  
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1)  
                * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));  
        s = s * EARTH_RADIUS;  
        double distance = s * 1000;  
        return distance;
	}

	public static void startNavigatorBaidu(double lat, double lon, String name) {
		if (isAppInstalled(Application.get(), PACKAGENAME_BAIDUMAP)) {
			try {
				StringBuilder uri = new StringBuilder();
				uri.append("intent://map/direction?destination=latlng:").
					append(lat).append(",").append(lon).append("|name:").append(name).
					append("&mode=driving&src=").append(Application.get().getString(R.string.app_name)).
					append("#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
				@SuppressWarnings("deprecation")
				Intent intent = Intent.getIntent(uri.toString());
				ActivityManager.get().currentActivity().startActivity(intent); // 启动调用
			} catch (URISyntaxException e) {
				Log.e("intent", e.getMessage());
			}
		} else {
			MToast.showToastMessage(R.string.baidumap_notinstalled);
		}
	}

	public static void startNavigatorAmap(double lat, double lon, String name) {
		if (isAppInstalled(Application.get(), PACKAGENAME_AMAP)) {
			try {
				Intent intent = new Intent("android.intent.action.VIEW",
						android.net.Uri
								.parse("androidamap://navi?sourceApplication=szzc&lat="
										+ lat + "&lon=" + lon + "&dev=0"));
				intent.setPackage(PACKAGENAME_AMAP);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				ActivityManager.get().currentActivity().startActivity(intent);
			} catch (Exception e) {
				Log.e("intent", e.getMessage());
			}
		} else {
			MToast.showToastMessage(R.string.amap_notinstalled);
		}
	}

	/**
	 * 检查手机上是否安装了指定的软件
	 * 
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean isAppInstalled(Context context, String packageName) {
		// 获取packagemanager
		final PackageManager packageManager = context.getPackageManager();
		// 获取所有已安装程序的包信息
		List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
		// 用于存储所有已安装程序的包名
		List<String> packageNames = new ArrayList<String>();
		// 从pinfo中将包名字逐一取出，压入pName list中
		if (packageInfos != null) {
			for (int i = 0; i < packageInfos.size(); i++) {
				String packName = packageInfos.get(i).packageName;
				packageNames.add(packName);
			}
		}
		// 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
		return packageNames.contains(packageName);
	}

}
